<template>
  <div class="process-list">
    <div class="page-header">
      <div class="header-left">
        <h2>流程管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createNewProcess">
          <el-icon><Plus /></el-icon>新建流程
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索流程名称"
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="statusFilter" placeholder="状态" clearable class="status-filter">
        <el-option label="全部" value="" />
        <el-option label="运行中" value="running" />
        <el-option label="已停止" value="stopped" />
        <el-option label="错误" value="error" />
      </el-select>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredProcesses"
      style="width: 100%"
      border
    >
      <el-table-column prop="name" label="流程名称">
        <template #default="{ row }">
          <div class="process-name">
            <el-icon><Connection /></el-icon>
            <span>{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="created_at" label="创建时间">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="editProcess(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button 
              :type="row.status === 'running' ? 'warning' : 'success'"
              @click="runProcess(row)"
            >
              <el-icon><VideoPlay v-if="row.status !== 'running'" /><VideoPause v-else /></el-icon>
              {{ row.status === 'running' ? '停止' : '运行' }}
            </el-button>
            <el-button type="danger" @click="deleteProcess(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建流程' : '编辑流程'"
      width="600px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="processForm.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="processForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入流程描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Search, Edit, Delete, Connection,
  VideoPlay, VideoPause
} from '@element-plus/icons-vue'
import { getProcessList, deleteProcess as deleteProcessApi, runProcess as runProcessApi } from '@/api/process'

const store = useStore()
const router = useRouter()

// 状态和数据
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const dialogVisible = ref(false)
const dialogType = ref('create')
const submitLoading = ref(false)
const processFormRef = ref(null)
const processList = ref([])

const processForm = ref({
  name: '',
  description: ''
})

const processRules = {
  name: [
    { required: true, message: '请输入流程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取流程列表
const fetchProcessList = async () => {
  try {
    loading.value = true
    const data = await getProcessList()
    processList.value = data
  } catch (error) {
    console.error('获取流程列表失败:', error)
    ElMessage.error('获取流程列表失败')
  } finally {
    loading.value = false
  }
}

// 计算属性
const filteredProcesses = computed(() => {
  return processList.value.filter(process => {
    const matchQuery = process.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchStatus = !statusFilter.value || process.status === statusFilter.value
    return matchQuery && matchStatus
  })
})

// 方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusType = (status) => {
  const types = {
    running: 'success',
    stopped: 'info',
    error: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    running: '运行中',
    stopped: '已停止',
    error: '错误'
  }
  return texts[status] || status
}

const resetForm = () => {
  processForm.value = {
    name: '',
    description: ''
  }
  if (processFormRef.value) {
    processFormRef.value.resetFields()
  }
}

const createNewProcess = () => {
  router.push('/process/editor')
}

const editProcess = (row) => {
  router.push(`/process/editor/${row.id}`)
}

const runProcess = async (row) => {
  try {
    await runProcessApi(row.id)
    ElMessage.success(`流程 ${row.name} 开始运行`)
  } catch (error) {
    console.error('运行流程失败:', error)
    ElMessage.error('运行流程失败')
  }
}

const deleteProcess = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该流程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteProcessApi(row.id)
    ElMessage.success('删除成功')
    fetchProcessList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除流程失败:', error)
      ElMessage.error('删除流程失败')
    }
  }
}

const handleSubmit = async () => {
  if (!processFormRef.value) return
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const response = await fetch('http://localhost:8000/api/process', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            name: processForm.value.name,
            description: processForm.value.description,
            data: {
              nodes: [],
              edges: []
            }
          })
        })
        
        if (!response.ok) {
          const error = await response.json()
          throw new Error(error.detail || '创建流程失败')
        }
        
        const data = await response.json()
        if (!data || typeof data.id !== 'number') {
          throw new Error('创建流程失败：服务器返回的数据格式不正确')
        }
        
        dialogVisible.value = false
        ElMessage.success('创建成功')
        // 确保使用数字类型的ID
        const processId = parseInt(data.id)
        if (isNaN(processId)) {
          throw new Error('创建流程失败：无效的流程ID')
        }
        router.push({
          name: 'process-edit',
          params: { id: processId.toString() }
        })
      } catch (error) {
        console.error('创建流程失败:', error)
        ElMessage.error(error.message || '创建流程失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

onMounted(() => {
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
  } else {
    fetchProcessList()
  }
})
</script>

<style lang="scss" scoped>
.process-list {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
  }
}

.search-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;

  .search-input {
    width: 300px;
  }

  .status-filter {
    width: 120px;
  }
}

.process-name {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-icon {
    color: #409EFF;
  }
}

:deep(.el-button-group) {
  .el-button {
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 